﻿using General.Core.Config;
using General.Entities.ViewData.Article;
using General.Mvc.Filters;
using General.Services.Article;
using General.Services.Template;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace General.Mvc.Controllers.Web
{
    [ServiceFilter(typeof(PageTemplateFilter))]
    public class SearchController : Controller
    {
        private readonly ITemplateService templateService;
        private readonly IArticleService articleService;
        private readonly IArticleCateService articleCateService;
        private readonly IMemoryCache memoryCache;
        public SearchController(ITemplateService templateService,
            IArticleService articleService,
            IArticleCateService articleCateService,
            IMemoryCache memoryCache)
        {
            this.templateService = templateService;
            this.articleService = articleService;
            this.articleCateService = articleCateService;
            this.memoryCache = memoryCache;
        }

        /// <summary>
        /// 搜索页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("/Search/{content}.html")]
        [Route("/Search")]
        public async Task<IActionResult> Index(string content)
        {
            var indexHtml = await templateService.GetPageHtmlContent(WebSiteTemplateConfig.Site_Template_Search_Info.name);
            var searchHtml = WebSiteTemplateConfig.Site_Template_Search_Info.htmlContent;
            var WebSite_UniqueIdentification = memoryCache.Get("WebSite_UniqueIdentification").ToString();

            indexHtml = indexHtml.Replace("@KeyWords", content).Replace("@Title", "搜索结果 - "+ content).Replace("@Description", "搜索结果 - " + content);

            searchHtml = searchHtml.Replace("@SearchContent", content);
            searchHtml = await SearchArticleResult(searchHtml,content);

            indexHtml = indexHtml.Replace("@Section_Main", searchHtml);
            HttpContext.Response.ContentType = "text/html";
            return Content(indexHtml);
        }

        /// <summary>
        /// 搜索文章表信息
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public async Task<string> SearchArticleResult(string html, string content)
        {
            StringBuilder OutHtml = new StringBuilder();
            MatchCollection mc = Regex.Matches(html, "(?<=(@Article_Start))[.\\s\\S]*?(?=(@Article_End))");
            foreach (Match m in mc)
            {
                var arr = m.Value.Split(",", StringSplitOptions.RemoveEmptyEntries);
                var parmList = new List<string>() { "", "" };
                for (int i = 0; i < arr.Length; i++)
                {
                    parmList[i] = arr[i];
                }
                List<SimpleArticleInfo> articleInfo = await articleService.GetNewList(Convert.ToInt32(parmList[1].Trim()), 1, null,content);

                foreach (var item in articleInfo)
                {
                    var temp = parmList[0].Replace("@Title", item.title).Replace("@Id", item.id.ToString()).Replace("@Thumb", item.thumb).Replace("@AuthorName", item.username).Replace("@AuthorImage", item.userImage).Replace("@CateName", item.cateName).Replace("@CateId", item.cateId.ToString()).Replace("@Time", item.creatTime).Replace("@Hits", item.hits.ToString());
                    OutHtml.Append(temp);
                }
            }
			if (mc.Count==0)
            {
                return html;
            }
            return Regex.Replace(html, "@Article_Start[.\\s\\S]*@Article_End", OutHtml.ToString(), RegexOptions.IgnoreCase);
        }



        /// <summary>
        /// 搜索接口
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("/Search/Api")]
        public async Task<IActionResult> Api(int page = 1, int limit = 10, string content="")
        {
            var data = JsonHelper.Serialize(await articleService.GetNewList(limit, page, null, content));
            return Content(data);
        }
    }
}
